package com.legend.utils;

import java.util.ArrayList;

import javax.servlet.http.HttpSession;

public class Token {
	private static final String TOKEN_LIST_NAME = "tokenList";
	public static final String TOKEN_STRING_NAME = "token";

	private static ArrayList getTokenList(HttpSession session) {
		Object obj = session.getAttribute(TOKEN_LIST_NAME);
		if (obj != null) {
			return (ArrayList) obj;
		} else {
			ArrayList tokenList = new ArrayList();
			session.setAttribute(TOKEN_LIST_NAME, tokenList);
			return tokenList;
		}
	}

	private static void saveTokenString(String tokenStr, HttpSession session) {
		ArrayList tokenList = getTokenList(session);
		tokenList.add(tokenStr);
		session.setAttribute(TOKEN_LIST_NAME, tokenList);
	}

	private static String generateTokenString() {
		return new Long(System.currentTimeMillis()).toString();
	}

	/**
	 * 生成token字符串，保存在session中，返回token字符串
	 * 
	 * @param HttpSession
	 *            session
	 * @return 返回一个token字符串
	 */
	public static String getTokenString(HttpSession session) {
		String tokenStr = generateTokenString();
		saveTokenString(tokenStr, session);
		return tokenStr;
	}

	/**
	 * 检查是不是合法的token字符串，如果session中包含token字符串，返回true，其它的返回false
	 * @param String
	 *            tokenStr
	 * @param HttpSession
	 *            session
	 * @return true: session contains tokenStr; false: session is null or
	 *         tokenStr is id not in session
	 */
	public static boolean isTokenStringValid(String tokenStr,
			HttpSession session) {
		boolean valid = false;
		if (session != null) {
			ArrayList tokenList = getTokenList(session);
			if (tokenList.contains(tokenStr)) {
				valid = true;
				tokenList.remove(tokenStr);
			}
		}
		return valid;
	}
}
